package com.emmmya.ocs.modules.system.file.controller;

import com.emmmya.ocs.modules.system.annotation.OperateLog;
import com.emmmya.ocs.common.utils.CommonUtil;
import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.vo.Result;
import com.emmmya.ocs.modules.system.file.entity.File;
import com.emmmya.ocs.modules.system.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件操作接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/assets")
public class FileController {
    @Autowired
    FileService fileService;

//    @ApiOperation(value = "获取所有文件接口")
    @RequestMapping(value = "/getAllFileList", method = RequestMethod.POST)
    @OperateLog(value="获取所有文件",operateType = 1,module = "文件模块")
    public Result<Object> getAllFileList(){
        List<File> list = fileService.getAllFileList();
        return ResultUtil.data(list,"获取了所有的文件");
    }

    // 上传文件接口
//    @ApiOperation(value = "上传文件接口")
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @OperateLog(value="上传文件",operateType = 2,module = "文件模块")
    public Result<Object> transportationCost(@RequestParam(value = "file",required = true) MultipartFile file,@RequestParam(value="curDirId",required=true) Long dirId) {
        //生成随机文件名
        String fKey = CommonUtil.renamePic(file.getOriginalFilename());
        File save = fileService.storeFile(file, fKey,dirId);
        return ResultUtil.data(save);
    }


    //删除文件
//    @ApiOperation(value = "删除文件接口")
    @RequestMapping(value = "/fileDelete", method = RequestMethod.POST)
    @OperateLog(value="删除文件",operateType = 4,module = "文件模块")
    public Result<Object> fileDelete(@RequestParam(value = "fileId",required = false) Long fileId){
        try {
            if(fileId == null){
                return ResultUtil.error("接收的参数有误，请重试！");
            }
            fileService.deleteAll(fileId);
        } catch (Exception e){
            return ResultUtil.success(e.getMessage());
        }
        return ResultUtil.success("删除成功");
    }

    @RequestMapping("/getFile/{fileName:.+}")
//    @ApiOperation(value = "查询文件接口")
    @OperateLog(value="下载文件",operateType = 6,module = "文件模块")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        //将文件作为资源加载
        File file = fileService.findByFKey(fileName);
        //获取文件数据源
        Resource resource = fileService.loadFileAsResource(fileName);
        String fileName1 = file.getFileName();
        //浏览器下载文件名(用于解决中文乱码问题)
        String downLoadName = null;
        //解决浏览器下载文件时候中文乱码问题
        try {
            downLoadName = URLEncoder.encode(fileName1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int i = fileName1.lastIndexOf(".");
        String fileType = fileName1.substring(i + 1, fileName1.length());
        // 尝试确定文件的内容类型
        String contentType = "";
        ResponseEntity<Resource> body = null;
        try {
            //如果是图片，则浏览器直接打开
            if (fileType.endsWith("png") || fileType.endsWith("gif") || fileType.endsWith("jpg")
                    || fileType.endsWith("bmp") || fileType.endsWith("jpeg")) {
                contentType = "image/" + fileType;
            } else {
                //其他类型文件，则告知浏览器下载
                contentType = file.getFileType();
            }
            body = ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downLoadName + "\"")
                    .body(resource);
        } catch (Exception ex) {
            log.info("无法确定文件类型。错误信息："+ex.getMessage());
        }

        return body;

    }

    @RequestMapping("/showFile/{fileName:.+}")
    @OperateLog(value="预览文件",operateType = 1,module = "文件模块")
    public ResponseEntity<Resource> showFile(@PathVariable String fileName, HttpServletRequest request) {
        //将文件作为资源加载
        Resource resource = fileService.loadFileAsResource(fileName);
        String filename = resource.getFilename();
        int i = filename.lastIndexOf(".");
        String fileType = filename.substring(i + 1, filename.length());
        String contentType = "image/" + fileType;
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(HttpHeaders.CONTENT_DISPOSITION).body(resource);
    }
}